﻿using ChessTest.Chess.Items;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using org.xisoft.game.utils.game;

namespace ChessTest.Chess
{
    /// <summary>
    /// 棋盘模型
    /// </summary>
    public partial class Chessboard: ChessBoardBase
    {


        /// <summary>
        /// 移动旗子
        /// </summary>
        /// <param name="chessman"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public bool Move(Chessman chessman, int x, int y)
        {

            if (!IsCheckCanMove || chessman.CanOriginMove(this,x, y))
            {
                CreateHitory(chessman, x, y);
                if (this[x, y] != null)
                    OnKill(chessman, this[x, y] as Chessman);

                MoveAction moveAction = new MoveAction { ToX = x, ToY = y, CurrentChessman = chessman };
                DoNextMove(moveAction);

                return true;
            }
            return false;
        }

        [DebuggerHidden]
        [DebuggerNonUserCode]
        [DebuggerStepThrough]
        public virtual void OnKill(Chessman killer, Chessman killed)
        {


        }

        [DebuggerHidden]
        [DebuggerNonUserCode]
        [DebuggerStepThrough]
        private void CreateHitory(Chessman chessman,int x,int y)
        {
            MoveAction history = new MoveAction()
            {
                CurrentChessman = chessman,
                OldChessman = GetChessman(x, y),
                FromX = chessman.PositionX,
                FromY = chessman.PositionY,
                ToX = x,
                ToY = y
            };
            if (history.OldChessman !=null)
            history.Score = history.OldChessman.Score;
            //historys.Push(history);

            //historyBoards.Push(GetKeyword());
        }


        protected override void Undo(MoveAction history)
        {

            this[history.FromX, history.FromY] = this[history.ToX, history.ToY];
            this[history.FromX, history.FromY].PositionX = history.FromX;
            this[history.FromX, history.FromY].PositionY = history.FromY;
            this[history.ToX, history.ToY] = history.OldChessman as Chessman;

        }


        public String GetKeyword()
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < MaxX; i++)
                for (int j = 0; j < MaxY; j++)
                {
                    Chessman chessman = GetChessman(i, j);
                    if (chessman != null)
                        sb.Append(chessman);
                }
            sb.Append(IsCurrentBlackMove?1:0);
            return sb.ToString();
        }

    }
}
